<?php

namespace App\Admin\Controllers;

use App;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use App\Models\WechatUser;
use App\Models\TestingUserRecord;
use App\Models\TestingDetail;
use App\Models\TestingItem;
use TestingXjbHelper;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Table;
use UserRecordService;
use UserTagService;
use WechatUserService;
use TestingDetailService;
use Excel;
class UserRecordController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('backend.user_record.title.list'));
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header(trans('backend.user_record.title.edit'));
            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('backend.user_record.title.add'));
            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(TestingUserRecord::class, function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');
            $this->buildGrid($grid);
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(TestingUserRecord::class, function (Form $form) {
            $form->text('key', trans('backend.user_record.column.key'))->rules('required');
            $form->text('value', trans('backend.user_record.column.value'))->rules('required');
            $form->text('tag', trans('backend.user_record.column.tag'))->rules('required');
        });
    }


    public function info($id,$tid)
    {
        return Admin::content(function (Content $content) use ($id,$tid) {
            $content->header(trans('backend.user_record.title.infor'));
            $title = TestingDetail::where('id',$tid)->value('name');
            $headers = ['题号','测评题目','提交答案'];
            $result = $this->formate($id,$tid);
            $answerstr = [];
            foreach($result as $k=>$v){
                $answer = implode(',',$v);
                $answerArr = explode(',',$answer);
                $answerstr[$k]=$answerArr;
            }

            $table = new Table($headers,$answerstr);
            $content->row((new Box($title,$table))->style('info')->solid());
        });
    }


    public function lightDecreaseWeightTesting(){
        return Admin::grid(TestingUserRecord::class, function (Grid $grid) {
//            $tid = TestingConfig::getValue('dw.testing.id',21);
            $grid->model()->decreaseWeight();
            $grid->model()->orderBy('id', 'desc');
            $this->buildGrid($grid);
        });
    }


    public function buildGrid($grid){
        $grid->id('ID')->sortable();
        $grid->user()->nick_name(trans('backend.user_record.column.uid'));
        $grid->detail()->name(trans('backend.user_record.column.tid'));
        $grid->score(trans('backend.user_record.column.score'));
        $grid->conclusion(trans('backend.user_record.column.conclusion'));
        $grid->created_at(trans('backend.user_record.column.creat_at'));

        $grid->rows(function($row){
            $row->actions()->add(function ($row) {
                return "<a href='/admin/testing/answers/info/{$row->id}/{$row->tid}'><i class='fa fa-eye'></i></a>";
            });
        });

        $grid->disablePerPageSelector();

        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->useModal();
//            $filter->is('uid',trans('backend.user_record.column.nick_name'))->select(WechatUserService::options()->pluck('nick_name','uid'));
            $filter->like('user.nick_name',trans('backend.user_record.column.nick_name'));
        });
        $grid->disableExport();
        $grid->disableCreation();

    }



    protected function formate($id,$tid){
        $res= TestingUserRecord::select('answers')->where(['id'=>$id,'tid'=>$tid])->first()->toarray();
        $answerArray =  TestingXjbHelper::strToArr($res['answers']);
        $indexArr = [];
        foreach($answerArray as $k => $v){
            $result = TestingItem::select('title','question_type')->where(['testing_id'=>$tid,'index'=>$v['index']])->first();
            $indexArr[$k]['index'] = $v['index'];
            $indexArr[$k]['title'] = $result['title'];
            //$indexArr[$k]['answer'] =$this->formateWeight($v['answer']);
            $indexArr[$k]['answer']= $v['answer'];
        }
        return $indexArr;
    }

    protected function formateWeight($str){
        $arr = explode("|||",$str);
        if(count($arr)>1){
            $str = implode(',',$arr);
        }
        return $str;
    }

    //中英测评导出结果
    public function exportRecipeTestingData($tid=24,$start='2016-01-01 00:00:00',$end='2116-01-01 00:00:00'){
        $userTag= UserTagService::getUserTagByTid($tid,$start,$end);
        $recordRes = UserRecordService ::getByTid($tid);
        $res = [];
        foreach($userTag as $k => $v){
            foreach($recordRes as $key => $value){
                if(strtotime($value['created_at'])-1 < strtotime($v['created_at']) && strtotime($v['created_at']) < strtotime($value['created_at'])+5){
                    $res[$k]['final_answers']=$value['final_answers'];
                    $res[$k]['tag'] = str_replace('|',',',$v['tag']);
                    $res[$k]['uid'] = $v['uid'];
                    //$res[$k]['record_time'] = $value['created_at'];
                    //$res[$k]['tag_time'] = $v['created_at'];
                }
            }
        }
        $list = [];
        $title = ['UID','性别','年龄','身高(cm)','体重(kg)','生育情况','从事特殊职业','家族病史或存在的健康问题','存在的肝病','存在的心血管类疾病','存在的消化道类疾病','存在的妇科疾病','存在的脑病','存在的肾病','存在的呼吸类疾病','存在的骨质类疾病','舌苔颜色','排便情况','睡眠情况','美体需求','美颜需求','工作强度','生存的外界环境','BMI','食谱标签'];
        array_push($list,$title);
        if($res){
            foreach($res as $k => $v){
                $row = [];
                array_push($row,$v['uid']);
                $answerArray =  TestingXjbHelper::strToArr($v['final_answers']);
                foreach($answerArray as $value){
                    array_push($row,$value['answer']);
                    if(count($row) == 24){
                        $row[23]=round($answerArray[22]['weight'],2);
                    }
                }
                array_push($row,$v['tag']);
                array_push($list,$row);
            }
        }
        $fileName = 'recipe-data-'.date('Y-m-h',time());
        Excel::create($fileName,function($excel) use ($list){
            $excel->sheet('个性食谱测评数据', function($sheet) use ($list){
                $sheet->rows($list);
            });
        })->export('xlsx');

    }




    public function exportDwAgeData($tid,$type=false){
        $testing ='轻体测年龄阶段分布';
        if($tid == 21){
            $testing ='21天轻体测年龄阶段分布';
        }elseif($tid == 19){
            $testing ='14天轻体测年龄阶段分布';
        }
        $start_time = "2017-02-15 22:00:00";
        $recordRes = UserRecordService ::getByTimeTid($tid,$start_time);
        $ageArr = [];
        foreach($recordRes as $k => $v){
            $answerArray =  TestingXjbHelper::strToArr($v['final_answers']);
            foreach($answerArray as $key => $value){
                if($value['index'] == 20){
                    $year = substr($value['answer'],0,4);
                    if($type){//原始数据
                        $age = 2017 - $year;
                        array_push($ageArr,$age);
                    }else{//过滤脏数据
                        if(strlen($year) == 4){//去除脏数据
                            $age = 2017 - $year;
                            if($age < 100){//去掉大于100岁的脏数据
                                array_push($ageArr,$age);
                            }
                        }
                    }
                }
            }
        }
        $list = [];
        $title = ['0-10','11-20','21-30','31-40','41-50','50+'];
        array_push($list,$title);
        $row=[0,0,0,0,0,0];
        foreach($ageArr as $k => $v){
            if($v >=0 && $v <= 10){
                $row[0] = $row[0]+1;
            }
            if($v >=11 && $v <= 20){
                $row[1] = $row[1]+1;
            }
            if($v >=21 && $v <= 30){
                $row[2] = $row[2]+1;
            }
            if($v >=31 && $v <= 40){
                $row[3] = $row[3]+1;
            }
            if($v >=41 && $v <= 50){
                $row[4] = $row[4]+1;
            }
            if($v >=51 ){
                $row[5] = $row[5]+1;
            }
        }
        array_push($list,$row);
        $fileName = 'userAge-data-'.date('Y-m-h',time());
        Excel::create($fileName,function($excel) use ($testing,$list){
            $excel->sheet($testing, function($sheet) use ($list){
                $sheet->rows($list);
            });
        })->export('xlsx');

    }


}
